<template>
  <el-popover class="select-icon-popover" :width="width" :placement="placement">
    <el-scrollbar :style="{height: scrollerHeight}" wrap-style="overflow-x: hidden;">
      <div class="icons">
        <div
          v-for="icon in icons" :key="icon"
          class="icon-item" :class="{active: selectedIcon === icon}"
          :style="selectedIcon === icon ? activeStyle : null"
          @click="onSelect(icon)"
        >
          <svg-icon :name="icon"></svg-icon>
        </div>
      </div>
    </el-scrollbar>

    <span slot="reference" class="popover-reference">
      <slot :selected-icon="selectedIcon"></slot>
    </span>
  </el-popover>
</template>

<script>
export default {
  name: 'select-icon',
  props: {
    value: String,
    placement: {
      type: String,
      default: 'bottom'
    },
    width: {
      type: Number,
      default: 400
    },
    height: {
      type: [String, Number],
      default: '300px'
    }
  },
  data () {
    return {
      icons: [],
      selectedIcon: this.value
    }
  },
  computed: {
    activeStyle () {
      const themeColor = this.$store.state.user.theme
      return {
        color: themeColor
      }
    },
    scrollerHeight () {
      const { height } = this
      return typeof height === 'string' ? height : height + 'px'
    }
  },
  watch: {
    value (val) {
      this.selectedIcon = val
    }
  },
  created () {
    this.icons = this.getIcons()
  },
  methods: {
    getIcons () {
      const icons = require.context('../../icons/svg', false, /\.svg$/)
      return icons.keys().map((v) => {
        const match = v.match(/\/(.*)\.svg$/)
        return match ? match[1] : ''
      })
    },
    onSelect (icon) {
      this.selectedIcon = icon
      this.$emit('selected', this.selectedIcon)
    }
  }
}
</script>

<style scoped>
.icon-item {
  display: inline-block;
  font-size: 1.6em;
  padding: .3em;
}
</style>
